import {
    getCurrentUserPagePermissionsApi,
    getCurrentUserPagePermissionsFail,
    getCurrentUserPagePermissionsSuccess
} from 'Shared/actions/currentUserContext';
import {PAGE_CODE} from './constants';
import * as api from './api';
/* =======================获取详情================================== */
export const GET_BRANDS_BEGIN = 'GET_BRANDS_BEGIN';
export const GET_BRANDS_SUCCESS = 'GET_BRANDS_SUCCESS';
export const GET_BRANDS_FAIL = 'GET_BRANDS_FAIL';
export const getBrandBegin = () => ({
    type: GET_BRANDS_BEGIN
});
export const getBrandSuccess = data => ({
    type: GET_BRANDS_SUCCESS,
    data
});
export const getBrandFail = () => ({
    type: GET_BRANDS_FAIL,
});

export const getBrands = condition => dispatch => {
    dispatch(getBrandBegin());
    return api.getBrands(condition).then(res => {
        if(res.ok)
            dispatch(getBrandSuccess(res.data));
        else
            dispatch(getBrandFail());
        return res.ok;
    });
};

//*==============================初始化API================================= */
export const getInitData = (code = PAGE_CODE) => dispatch => {
    const init = dispatch(getBrands());
    const permissions = getCurrentUserPagePermissionsApi(code).then(res => {
        if(res.isOk) dispatch(getCurrentUserPagePermissionsSuccess(res.data));
        else dispatch(getCurrentUserPagePermissionsFail(res.statusCode, res.message));
        return res.isOk;
    });
    return Promise.all([init, permissions]).then(values => values[0] && values[1]);
};
/*==============================查询列表================================= */

export const GET_LIST_BEGIN = 'GET_LIST_BEGIN';
export const GET_LIST_SUCCESS = 'GET_LIST_SUCCESS';
export const GET_LIST_FAIL = 'GET_LIST_FAIL';
export const getListBegin = () => ({
    type: GET_LIST_BEGIN
});
export const getListSuccess = (data, condition) => ({
    type: GET_LIST_SUCCESS,
    data,
    condition
});
export const getListFail = () => ({
    type: GET_LIST_FAIL,
}); //获取列表

export const getList = condition => dispatch => {
    dispatch(getListBegin());
    const {dealerCode, dealerName, ...props} = condition;
    return api.getList(props).then(res => {
        if(res.ok)
            dispatch(getListSuccess(res.data, condition));
        else
            dispatch(getListFail());
        return res.ok;
    });
}; //按钮搜索

export const querySearch = () => (dispatch, getState) => {
    const condition = getState()
        .getIn(['page', 'appState', 'queryCondition'])
        .toJS();
    return dispatch(getList(condition));
}; //分页排序搜索

export const tableSearch = page => (dispatch, getState) => {
    const query = getState()
        .getIn(['page', 'appState', 'queryBySort'])
        .toJS();
    const condition = Object.assign({}, query, page);
    return dispatch(getList(condition));
};

export const querySearchSAP = () => (dispatch, getState) => {
    const condition = getState()
        .getIn(['page', 'appState', 'queryCondition'])
        .toJS();
    const {sapDeliveryCodes, pageIndex, pageSize, isDesc, sortField} = condition;
    dispatch(getListBegin());
    return api.getListSAP({
        sapDeliveryCodes,
        pageIndex,
        pageSize,
        isDesc,
        sortField
    }).then(res => {
        if(res.ok)
            dispatch(getListSuccess(res.data, condition));
        else
            dispatch(getListFail());
        return res.ok;
    });
};

/*==============================导出================================= */
export const exportData = () => (dispatch, getState) => {
    const {dealerCode, dealerName, pageIndex, pageSize, isDesc, sortField, ...props} = getState()
        .getIn(['page', 'appState', 'queryCondition'])
        .toJS() || {};
    return api.exportInfo(props);
};

/*==============================查询action================================= */
//修改查询条件

export const SAVE_QUERY_CONDITION = 'SAVE_QUERY_CONDITION';
export const saveQueryCondition = (name, value) => ({
    type: SAVE_QUERY_CONDITION,
    name,
    value
});
//重置查询条件

export const RESET_QUERY_PANEL = 'RESET_QUERY_PANEL';
export const resetQueryPanel = () => ({
    type: RESET_QUERY_PANEL,
});

/*==========================修改新增编辑页数据================================= */
export const SAVE_SUBMIT_CONDITION = 'SAVE_SUBMIT_CONDITION';

export const saveSubmitCondition = (name, value) => ({
    type: SAVE_SUBMIT_CONDITION,
    name,
    value
});
/* =======================获取详情================================== */
export const GET_DETAIL_BEGIN = 'GET_DETAIL_BEGIN';
export const GET_DETAIL_SUCCESS = 'GET_DETAIL_SUCCESS';
export const GET_DETAIL_FAIL = 'GET_DETAIL_FAIL';
export const getDetailBegin = () => ({
    type: GET_DETAIL_BEGIN
});
export const getDetailSuccess = data => ({
    type: GET_DETAIL_SUCCESS,
    data
});
export const getDetailFail = () => ({
    type: GET_DETAIL_FAIL,
});

export const getDetail = id => dispatch => {
    dispatch(getDetailBegin());
    return api.getDetail(id).then(res => {
        if(res.ok)
            dispatch(getDetailSuccess(res.data));
        else
            dispatch(getDetailFail());
        return res.ok;
    });
};

export const getEditInit = pid => (dispatch, getState) => {
    dispatch(getDetailBegin());
    return api.getDetail(pid).then(res => {
        if(res.ok)
            return api.getSaleOrderDetail(res.data.partSaleOrderId).then(resp => {
                if(resp.ok) {
                    const {details = []} = resp.data;
                    const content = res.data.details || [];
                    const newDetails = content.map(item => {
                        const {oldPartId, oldPartCode, oldPartName} = item;
                        const parts = details.map(p => ({
                            value: p.partId,
                            text: `(${p.partCode})${p.partName}`,
                        }));
                        return {
                            ...item,
                            parts: oldPartId ? parts.concat(...[{
                                value: oldPartId,
                                text: `(${oldPartCode})${oldPartName}`,
                            }]) : parts
                        };
                    });
                    dispatch(getDetailSuccess({
                        ...res.data,
                        details: newDetails
                    }));
                } else
                    dispatch(getDetailFail());
                return resp.ok;
            });
        dispatch(getDetailFail());
        return res.ok;
    });
};
/*==============================清除数据================================= */
export const CLEAR_DATA = 'CLEAR_DATA';
export const clearData = () => ({
    type: CLEAR_DATA
});

export const onClickUpdate = id => (dispatch, getState) => {
    const {
        remark,
        rowVersion,
        details = [],
    } = getState()
        .getIn(['page', 'appState', 'submitData'])
        .toJS();
    return api.updateInfo(id, {
        details: details.map(item => ({
            id: item.id,
            oldPartId: item.oldPartId ? item.oldPartId : undefined
        })),
        remark,
        rowVersion,
    });
};

export const SELECT_DATA = 'SELECT_DATA';
export const selectData = data => ({
    type: SELECT_DATA,
    data
});

export const SELECT_DEALER_QUERY = 'SELECT_DEALER_QUERY';
export const selectDealer = data => ({
    type: SELECT_DEALER_QUERY,
    data: {
        dealerId: data.id,
        dealerCode: data.code,
        dealerName: data.name,
    }
});

export const UPDATE_DETAIL = 'UPDATE_DETAIL';
export const updateDetails = data => ({
    type: UPDATE_DETAIL,
    data
});
